<?php

// Namespace

namespace Loop;


/**
 * CApiFactory
 *
 * @package		Loop
 * @category	Factory
 */

class CApiFactory
{
	/**
	 *
	 */

	public function run($className, $apiName, $extensionId)
	{
		// Create an object
		
		if
		(
			($extensionId == EXTENSION_LOOP) &&
			($className == 'CApplication')
		)
		{
			// CApplication needs a special instantiation since it's a singleton
			
			$object = app();
		}
		else
		{
			try
			{
				// Does the model exist?
				
				$pathToModel = app()->getPathHelper()->getPathToModel($className , $extensionId);

				if (file_exists($pathToModel) === false)
				{
					e
					(
						EXCEPTION_MODEL_NOT_FOUND,
						array
						(
							'className' => $className,
							'pathToModel' => $pathToModel,
							'extensionId' => $extensionId
						)
					);
				}
				
				
				// Create the model
				
				require_once($pathToModel);


				// Is there a namespace ?

				$classObject = $className;

				if (class_exists($className) === false)
				{
					$namespace = str_replace('-', '\\', $extensionId);

					$classObject = $namespace . '\\' . $className;
				}

				$object = new $classObject();
			}
			catch (\Exception $e)
			{
				// The model couldn't be found

				if ($e->getCode() == EXCEPTION_MODEL_NOT_FOUND)
				{
					// Try with a class instead
					
					$pathToClass = app()->getPathHelper()->getPathToClass($className, $extensionId);

					if (file_exists($pathToClass) == false)
					{
						e
						(
							EXCEPTION_CLASS_NOT_FOUND,
							array
							(
								'className' => $className,
								'pathToClass' => $pathToClass
							)
						);
					}
					
					
					// Create the class
					
					require_once($pathToClass);

					// Is there a namespace ?

					$classObject = $className;
					
					if (class_exists($className) === false)
					{
						$namespace = str_replace('-', '\\', $extensionId);

						$classObject = $namespace . '\\' . $className;
					}					
					
					$object = new $classObject();
				}
				else
				{
					throw $e;
				}
			}
		}
		
		
		// Does the method exist?
		
		$methodName = 'api_' . $apiName;

		if (is_callable(array($object, $methodName)) == false)
		{
			e
			(
				EXCEPTION_API_NOT_FOUND,
				array
				(
					'apiName' => $apiName,
					'className' => $className,
					'extensionId' => $extensionId
				)
			);
		}


		// Call the method

		return $object->$methodName();		
	}
}

?>
